/**
 * 步骤2测试：同意条款（onClickStartApplication -> 个人信息页）
 */

import { mkdir, readFile, writeFile } from 'node:fs/promises'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { getPageParser } from '../src/main/automation/page-parser'
import { loadConfig } from '../src/main/config/index'
import { setupLogger } from '../src/main/logger/index'
import { HttpSession } from '../src/main/request/http-session'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const projectRoot = join(__dirname, '..')

const BASE_URL = 'https://abs1.td.gov.hk/tdab2/tdabs_external/AdminServlet_tchinese'
const SNAPSHOT_DIR = join(projectRoot, 'test-steps-snapshots')

async function saveSnapshot(name: string, html: string, metadata: any = {}) {
  await mkdir(SNAPSHOT_DIR, { recursive: true })
  const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
  const filename = `${timestamp}_step02_${name}.html`
  const filepath = join(SNAPSHOT_DIR, filename)
  await writeFile(filepath, html, 'utf8')
  console.log(`  ✓ 快照已保存: ${filename}`)
  return filepath
}

async function loadStep1Result() {
  // 查找最新的步骤1快照
  const files = await import('node:fs/promises')
  const dir = await files.readdir(SNAPSHOT_DIR)
  const step1Files = dir.filter(f => f.includes('step01_home') && f.endsWith('.html')).sort().reverse()

  if (step1Files.length === 0) {
    throw new Error('未找到步骤1的快照文件，请先运行步骤1测试')
  }

  const latestFile = join(SNAPSHOT_DIR, step1Files[0])
  const html = await readFile(latestFile, 'utf8')
  const parser = getPageParser()
  const formFields = parser.extractFormFields(html, 'frmAppointment')

  return { html, formFields }
}

function checkPage(html: string, stepName: string): { success: boolean, details: Record<string, boolean> } {
  const checks = {
    hasCmdStartNewApplication: html.includes('cmdStartNewApplication'),
    isTermsPage: html.includes('條款') || html.includes('条款'),
    hasAgreeCheckbox: html.includes('agree') || html.includes('checkbox'),
    hasContinueButton: html.includes('繼續') || html.includes('继续') || html.includes('onClickStartApplication'),
    hasForm: html.includes('form') && html.includes('frmAppointment'),
    isPersonalInfoPage: html.includes('cmdInputPersonalInfo') || html.includes('選擇服務') || html.includes('选择服务'),
  }

  console.log(`\n📄 页面检查: ${stepName}`)
  console.log('─'.repeat(60))
  for (const [key, value] of Object.entries(checks)) {
    const icon = value ? '✓' : '✗'
    const label = key.replace(/([A-Z])/g, ' $1').trim()
    console.log(`  ${icon} ${label}`)
  }

  // 成功判断：要么是条款页（第一步），要么是个人信息页（第二步完成）
  const success = checks.hasForm && (checks.isTermsPage || checks.isPersonalInfoPage)
  return { success, details: checks }
}

async function testStep2() {
  console.log('步骤2测试：同意条款（onClickStartApplication -> 个人信息页）')
  console.log('='.repeat(60))

  await loadConfig()
  await setupLogger()

  // 加载步骤1的结果
  console.log('\n📂 加载步骤1结果...')
  const step1Result = await loadStep1Result()
  const step1Fields = step1Result.formFields.success && step1Result.formFields.data ? step1Result.formFields.data : {}
  console.log(`  从步骤1提取字段数: ${Object.keys(step1Fields).length}`)

  const session = new HttpSession()

  // 子步骤2.1: 从首页点击"开始预约"进入条款页
  console.log('\n子步骤2.1: 从首页点击"开始预约"进入条款页')
  console.log('─'.repeat(60))

  const payload1: Record<string, string> = {
    ...step1Fields,
    storedAppointmentOperation: 'A',
    timestamp: Date.now().toString(),
  }

  const url1 = `${BASE_URL}?cmd=cmdStartNewApplication`
  console.log(`请求: POST ${url1}`)
  console.log(`  载荷字段数: ${Object.keys(payload1).length}`)

  const response1 = await session.postForm(url1, payload1, `${BASE_URL}?cmd=cmdShowHome`)
  const check1 = checkPage(response1.body, '条款页响应')

  await saveSnapshot('terms', response1.body, {
    step: '2.1',
    url: response1.url,
    status: response1.status,
    check: check1,
  })

  if (!check1.success) {
    console.log('\n❌ 子步骤2.1失败：未到达条款页')
    process.exit(1)
  }

  // 子步骤2.2: 同意条款，进入个人信息页（服务选择状态）
  // 注意：onClickStartApplication()会设置action为cmdInputPersonalInfo并提交
  console.log('\n子步骤2.2: 同意条款，进入个人信息页（服务选择状态）')
  console.log('─'.repeat(60))

  const parser = getPageParser()
  const termsFields = parser.extractFormFields(response1.body, 'frmAppointment')
  const termsFieldsData = termsFields.success && termsFields.data ? termsFields.data : {}

  // 构造同意条款的表单（对齐doOutput和onClickStartApplication的逻辑）
  // doOutput()检查checkbox是否选中，然后调用onClickStartApplication()
  // onClickStartApplication()设置action为cmdInputPersonalInfo并提交
  const payload2: Record<string, string> = {
    ...termsFieldsData,
    storedAppointmentOperation: 'A',
    checkbox: 'checkbox', // 勾选checkbox
    timestamp: Date.now().toString(),
  }

  const url2 = `${BASE_URL}?cmd=cmdInputPersonalInfo`
  console.log(`请求: POST ${url2}`)
  console.log(`  载荷字段数: ${Object.keys(payload2).length}`)
  console.log(`  checkbox: 已勾选`)

  const response2 = await session.postForm(url2, payload2, response1.url)
  const check2 = checkPage(response2.body, '个人信息页响应（服务选择状态）')

  await saveSnapshot('personal_info', response2.body, {
    step: '2.2',
    url: response2.url,
    status: response2.status,
    check: check2,
    note: '个人信息页初始状态（显示服务选择按钮）',
  })

  // 检查是否有DI服务选项
  const hasDIService = response2.body.includes('onClickDISevType') || response2.body.includes('免試簽發')
  console.log(`\n  ${hasDIService ? '✓' : '✗'} 检测到DI服务选项`)

  if (!check2.success || !check2.details.isPersonalInfoPage) {
    console.log('\n❌ 子步骤2.2失败：未到达个人信息页')
    process.exit(1)
  }

  if (!hasDIService) {
    console.log('\n⚠️  警告：未检测到DI服务选项，页面可能不正确')
  }

  console.log('\n✓ 步骤2成功：已进入个人信息页（服务选择状态）')
  console.log(`\n📁 快照目录: ${SNAPSHOT_DIR}`)
}

testStep2().catch((error) => {
  console.error('\n❌ 测试失败:', error)
  process.exit(1)
})
